package ks.app.smartDic;

import java.util.ArrayList;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.os.Bundle;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.Toast;

public class PreferenceUI extends PreferenceActivity {

	SharedPreferences sp;
	SharedPreferences.Editor spe;
	Boolean PrefNotification;

	CheckBoxPreference Preferences;
	CheckBoxPreference prefSuperCacheing;
	CheckBoxPreference prefSuperVolumeCacheing;
	ListPreference prefResultView;
	ListPreference prefSortOfDictionary;
	ListPreference googleID;

	private static final int NOTIFICATION_ID = 1;
	NotificationManager notifier;
	Notification notify;
	Intent toLaunch;
	PendingIntent intentBack;

	String[] gmailArray;

	GoogleAnalyticsTracker tracker;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		addPreferencesFromResource(R.layout.preferenceui);

		sp = getSharedPreferences("PrefSmartDic", 0);

		Preferences = (CheckBoxPreference) findPreference("prefStatusBar");

		PrefNotification = sp.getBoolean("PrefNotification", false);
		Preferences.setChecked(PrefNotification);

		Preferences
				.setOnPreferenceClickListener(new OnPreferenceClickListener() {

					@Override
					public boolean onPreferenceClick(Preference preference) {
						if (!getPrefNotification()) {

							notifier = (NotificationManager) getApplicationContext()
									.getSystemService(
											Context.NOTIFICATION_SERVICE);
							notify = new Notification(R.drawable.smartdic_icon,
									"스마트 영어사전", System.currentTimeMillis());
							toLaunch = new Intent(getApplicationContext(),
									SearchView.class);

							String prefSortOfDictionary = sp
									.getString(
											getString(R.string.PREF_SORT_OF_DICTIONARY),
											"영한사전");

							toLaunch.putExtra(
									getString(R.string.SORT_OF_DICTIONARY),
									getSortOfDictionary(prefSortOfDictionary));

							intentBack = PendingIntent.getActivity(
									getApplicationContext(), 0, toLaunch, 0);

							notify.flags = notify.flags
									| Notification.FLAG_ONGOING_EVENT;

							notify.setLatestEventInfo(getApplicationContext(),
									"스마트 영어사전", "단어를 검색하고 싶으면 여기를 클릭!",
									intentBack);

							notifier.notify(NOTIFICATION_ID, notify);

							setPrefNotification(true);

						} else {

							try {
								notifier.cancel(NOTIFICATION_ID);
							} catch (Exception e) {
								ksLog.d("exception", e.getMessage());
							}
							setPrefNotification(false);
						}
						return false;
					}
				});

		prefSuperCacheing = (CheckBoxPreference) findPreference("prefSuperCacheing");
		Boolean isSuperCacheing = sp.getBoolean("PrefSuperCacheing", true);
		prefSuperCacheing.setChecked(isSuperCacheing);

		prefSuperCacheing
				.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

					@Override
					public boolean onPreferenceChange(Preference preference,
							Object newValue) {

						spe = sp.edit();
						spe.putBoolean("PrefSuperCacheing", (Boolean) newValue);
						spe.commit();

						return true;
					}
				});

		prefSuperVolumeCacheing = (CheckBoxPreference) findPreference("prefSuperVolumeCacheing");
		Boolean isSuperVolumeCacheing = sp.getBoolean(
				"PrefSuperVolumeCacheing", true);
		prefSuperVolumeCacheing.setChecked(isSuperVolumeCacheing);

		prefSuperVolumeCacheing
				.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

					@Override
					public boolean onPreferenceChange(Preference preference,
							Object newValue) {

						spe = sp.edit();
						spe.putBoolean("PrefSuperVolumeCacheing",
								(Boolean) newValue);
						spe.commit();

						return true;
					}
				});

		prefResultView = (ListPreference) findPreference("list_preference");
		prefResultView
				.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

					@Override
					public boolean onPreferenceChange(Preference preference,
							Object newValue) {
						spe = sp.edit();
						spe.putString(getString(R.string.PREF_RESULT_VIEW),
								String.valueOf(newValue));
						spe.commit();
						return false;
					}
				});

		/*
		prefSortOfDictionary = (ListPreference) findPreference("list_dictionary");
		prefSortOfDictionary
				.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

					@Override
					public boolean onPreferenceChange(Preference arg0,
							Object newValue) {

						spe = sp.edit();
						spe.putString(
								getString(R.string.PREF_SORT_OF_DICTIONARY),
								String.valueOf(newValue));
						spe.commit();

						return false;
					}
				});
		 */

		googleID = (ListPreference) findPreference("googleID");

		AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
		Account[] list = manager.getAccounts();
		ArrayList<String> gmailList = new ArrayList<String>();

		for (Account account : list) {
			if (account.type.equalsIgnoreCase("com.google")) {
				gmailList.add(account.name);
			}
		}

		gmailArray = gmailList.toArray(new String[gmailList.size()]);

		googleID.setEntries(gmailArray);
		googleID.setEntryValues(gmailArray);

		googleID.setOnPreferenceClickListener(new OnPreferenceClickListener() {

			@Override
			public boolean onPreferenceClick(Preference arg0) {

				if (gmailArray.length == 0) {
					
					Toast.makeText(getApplicationContext(),
							"휴대폰 설정에서 구글ID를 등록해 주세요.", Toast.LENGTH_SHORT)
							.show();
				}
				
				Toast.makeText(getApplicationContext(),
						"곧 업데이트 될 단어장을 위해 구글ID를 확인합니다.", Toast.LENGTH_SHORT)
						.show();

				return false;
			}
		});

		googleID.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

			@Override
			public boolean onPreferenceChange(Preference arg0, Object newValue) {

				spe = sp.edit();
				spe.putString(getString(R.string.PREF_GOOGLE_ID),
						String.valueOf(newValue));
				spe.commit();

				Toast.makeText(getApplicationContext(), newValue + "로 연동합니다.",
						Toast.LENGTH_SHORT).show();

				return true;

			}
		});

		tracker = GoogleAnalyticsTracker.getInstance();
		tracker.start("UA-22873894-1", 20, this);
		tracker.trackPageView("/preference");
		tracker.dispatch();

	}

	public void setPrefNotification(Boolean flag) {
		spe = sp.edit();
		spe.putBoolean("PrefNotification", flag);
		spe.commit();
	}

	public Boolean getPrefNotification() {
		PrefNotification = sp.getBoolean("PrefNotification", false);
		return PrefNotification;
	}

	private String getSortOfDictionary(String str) {

		ksLog.d("yes", str);

		if (str.compareTo("영한사전") == 0) {
			return getString(R.string.ENG_TO_KOREAN);
		} else if (str.compareTo("한영사전") == 0) {
			return getString(R.string.KOREAN_TO_ENG);
		} else if (str.compareTo("영영사전") == 0) {
			return getString(R.string.ENG_TO_ENG);
		} else if (str.compareTo("국어사전") == 0) {
			return getString(R.string.KOREAN_TO_KOREAN);
		}

		return null;
	}
}
